<?php
namespace Admin\Controller;

class FileController extends CommonController {
	public $upload_ext_str = '';

	public function _initialize(){
		$session_name = session_name();
		$session_id   = $_POST[$session_name];
		if(empty($session_id) == false && $session_id != session_id()){
		    session_destroy();
			session_id($session_id);
			@session_start();    
		}
		parent::_initialize();
		$upload_ext_str       = $this->_get('upload_file_ext');
		$upload_ext_arr       = explode(',', $upload_ext_str);
		$upload_ext           = $upload_ext_str ? '*.' . implode(';*.', $upload_ext_arr) . ';' : '';
		$this->upload_ext_str = $upload_ext_str;
		
		$img_ext = '*.' . implode(';*.', D('File')->img_ext) . ';';
		$all_ext = '*.' . implode(';*.', D('File')->all_ext) . ';';

		$upload_type = $this->_get('upload_type');
		$upload_type = $upload_ext_str ? 'custom' : $upload_type;

		$this->assign('img_ext', $img_ext);
		$this->assign('all_ext', $all_ext);
		$this->assign('file_exts', $upload_ext);
		$this->assign('is_multi', $this->_get('is_multi'));
		$this->assign('upload_name', $this->_get('upload_name'));
		$this->assign('upload_type', $upload_type);
		$this->assign('upload_field', $this->_get('upload_field'));
		$this->assign('upload_file_ext', $this->_get('upload_file_ext'));
	}
	/**
	 * 文件上传
	 */
	public function upload(){
		if(!empty($_FILES)){
			$type       = 'file';
			$tempFile   = $_FILES['Filedata']['tmp_name'];
			$pathinfo   = pathinfo($_FILES['Filedata']['name']);
			$ext        = strtolower($pathinfo['extension']);
			if(in_array($ext, array('php', 'asp', 'html', 'htm', 'sh', 'bash'))){
				exit('err');
			}
			$filename   = md5($pathinfo['basename'] . uniqid()) . "." . $ext;
			$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/';
			$new_file   = "/Uploads/" . $type . "/" . date("Ymd") . '/' . $filename;
			$targetFile = str_replace('//', '/', $targetPath) . $new_file;
			mkdir(str_replace($filename, '', $targetFile), 0777, true);
			if (@move_uploaded_file($tempFile, $targetFile)){
				$fileinfo['filename']    = $pathinfo['basename'];//原文件名
				$fileinfo['savename']    = $filename;//保存文件名
				$fileinfo['filepath']    = $new_file;
				$fileinfo['ext']         = $ext;
				$fileinfo['size']        = $_FILES['Filedata']['size'];
				$fileinfo['create_time'] = time();
				$fileinfo['user_id']     = $this->_user_id;
				$model = D('file');
				$model->add($fileinfo);
				$file_id = $model->getLastInsID();

				$fileinfo['file_id']   = $file_id;
				$fileinfo['file_path'] = $model->get_path($file_id);
				$fileinfo['is_pic']    = in_array($ext, D('File')->img_ext);
				$fileinfo['file_url']  = in_array($ext, D('File')->img_ext) ? $model->get_path($file_id, 200, 200) : $model->get_path('icon-file.png', 200, 200);

				header('Content-Type:application/json; charset=utf-8');
				exit(json_encode($fileinfo));
			}else{
			 	exit('err');
			}
		}
	}
	public function win_upload(){
		$this->display();
	}
	public function win_online(){
		//分页参数
		$page      = $this->_get('p', '', 1);
		$pagesize  = $this->_get('pagesize', '', 15);
		$first_row = $pagesize * ($page - 1);

		$upload_type = $this->_get('upload_type');
		if($upload_type == 'img'){
			$where['ext'] = array('in', implode(',', D('File')->img_ext));
		}
		if($this->upload_ext_str){
			$where['ext'] = array('in', $this->upload_ext_str);
		}

		$count = D('File')->where($where)->count();
		$list  = D('File')->where($where)->order('create_time desc')->limit($first_row . ',' . $pagesize)->select();
		foreach ($list as $rs) {
			$rs['file_id']   = $rs['id'];
			$rs['file_path'] = D('File')->get_path($rs['id']);
			$rs['file_url']  = in_array($rs['ext'], D('File')->img_ext) ? D('File')->get_path($rs['id'], 200, 200) : D('File')->get_path('icon-file.png', 200, 200);
			$rs['is_pic']    = in_array($rs['ext'], D('File')->img_ext);
			$file_list[] = $rs;
		}
		//处理AJAX分页
		$this->ajax_page($file_list, $count, 'file_list');
		
		$this->assign('list', $file_list);
		$this->display();
	}
	public function ueditor_uploads(){
		$ueditor_php_path = 'Public/Js/ueditor/php/';
		date_default_timezone_set("Asia/chongqing");
		error_reporting(E_ERROR);
		header("Content-Type: text/json; charset=utf-8");
		
		$upload_path = 'manage';
		$config_json = file_get_contents($ueditor_php_path . "config.json");
		$config_json = str_replace('/Uploads/ueditor/', '/Uploads/ueditor/'.$upload_path.'/', $config_json);
		$CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", $config_json), true);
		$action = $_GET['action'];

		switch ($action) {
		    case 'config':
		        $result =  json_encode($CONFIG);
		        break;

		    /* 上传图片 */
		    case 'uploadimage':
		    /* 上传涂鸦 */
		    case 'uploadscrawl':
		    /* 上传视频 */
		    case 'uploadvideo':
		    /* 上传文件 */
		    case 'uploadfile':
		        $result = include($ueditor_php_path . "action_upload.php");
		        break;

		    /* 列出图片 */
		    case 'listimage':
		        $result = include($ueditor_php_path . "action_list.php");
		        break;
		    /* 列出文件 */
		    case 'listfile':
		        $result = include($ueditor_php_path . "action_list.php");
		        break;

		    /* 抓取远程文件 */
		    case 'catchimage':
		        $result = include($ueditor_php_path . "action_crawler.php");
		        break;

		    default:
		        $result = json_encode(array(
		            'state'=> '请求地址出错'
		        ));
		        break;
		}

		/* 输出结果 */
		if (isset($_GET["callback"])) {
		    if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
		        echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
		    } else {
		        echo json_encode(array(
		            'state'=> 'callback参数不合法'
		        ));
		    }
		} else {
		    echo $result;
		}
	}
}
?>